<?php
namespace app\controller;

use app\BaseController;
use app\model\Banner;

class BannerController extends BaseController
{
    public function getBannerAll()
    {
        $param = $this->request->param();
        $page=$param['page'];
        $db = new Banner();
        $data =$db->pageFindAll($page);
        $json=array('data'=>$data,'code'=>0,'tips'=>'ok');
        return json($json, 200);
    }

    public function insert()
    {
        $param = $this->request->param();
        $name = $param->name;
        $imageUrl = $param->imageUrl;
        $bState = $param->state;
        $data=[
           'name'=>$name,
           'imageUrl'=>$imageUrl,
           'createTime'=>time(),
           'updateTime'=>time(),
           'bState'=>$bState,
        ];
        $db = new Banner();
        if ($db->add($data)) {
            $json=array('data'=>[],'code'=>0,'tips'=>'ok');
        } else {
            $json=array('data'=>[],'code'=>2001,'tips'=>'新增banner图失败');
        }
        return json($json, 200);
    }
    public function findById($id)
    {
        $db = new Banner();
        $data = $db->findById($id);
        if (!$data->isEmpty()) {
            $json=array('data'=>$data,'code'=>0,'tips'=>'ok');
        } else {
            $json=array('data'=>[],'code'=>2002,'tips'=>'没有查询到数据');
        }
        return json($json, 200);
    }

    public function update()
    {
        $param = $this->request->param();
        // var_dump($param);
        // var_dump($param["name"]);
        $name = $param['name'];
        $imageUrl = $param['imageUrl'];
        $bState = $param['bState'];
        $data =[
            'name'=>$name,
            'imageUrl'=>$imageUrl,
            'updateTime'=>time(),
            'bState'=>$bState,
         ];
        if (isset($param['bannerId'])) {
            $data['bannerId']=$param['bannerId'];
        } else {
            $data['createTime']=time();
        }
        $db = new Banner();
        if (isset($data['bannerId'])) {
            if ($db->updateBanner($data)) {
                $json=array('data'=>[],'code'=>0,'tips'=>'ok');
            } else {
                $json=array('data'=>[],'code'=>2002,'tips'=>'更新失败');
            }
        } else {
            if ($db->add($data)) {
                $json=array('data'=>[],'code'=>0,'tips'=>'ok');
            } else {
                $json=array('data'=>[],'code'=>2001,'tips'=>'新增banner图失败');
            }
        }
        return json($json, 200);
        // return json([], 200);
    }

    public function deleteData($id)
    {
        $db = new Banner();
        $db->deleteBanner($id);
        return json(['data'=>[],'code'=>0,'tips'=>'ok'], 200);
    }
}
